import requests
import json
import pandas as pd
import random
import time

df = pd.DataFrame()

# 写入Excel文件，如果文件不存在，将会创建一个新文件
excel_filename = 'code.xlsx'
df.to_excel(excel_filename, index=False, header=False)

# 指定的工作表
df1 = pd.read_excel('知识体系_机器学习.xlsx')
df2 = pd.read_excel('问答.xlsx')

konwledge_list = df1.iloc[:, 2]
question_list = df2.iloc[:, 1]

# 目标URL
url = "http://localhost:5000/buildQuestion"


def build_request():
    model_list = ["spark", "kimi", "tongyi"]
    question_type_list = [1, 2, 3, 4, 5]
    mode_list = [1, 2, 3]
    grade_list = [0, 1, 2]
    # 要发送的JSON数据
    model_name = random.choice(model_list)
    # question_type = random.choice(question_type_list)
    question_type = 6
    mode = random.choice(mode_list)
    knowledge = random.choice(konwledge_list)
    grade = random.choice(grade_list)
    question = random.choice(question_list)
    if mode == 1 or mode == 2:
        data = {
            "model_name": model_name,
            "question_type": question_type,
            "mode": mode,
            "knowledge": [
                knowledge
            ],
            "template": "",
            "question_num": 1,
            "grade": grade,
            "text": question,
            "timeLimit": "100ms",
            "spaceLimit": "1M",
            "time_complexity": "o(n)",
            "space_complexity": "o(n)",
            "code_type": "python",
            "input_range": "none"
        }

    else:
        data = {
            "model_name": model_name,
            "question_type": question_type,
            "mode": mode,
            "knowledge": [
                knowledge
            ],
            "template": "",
            "question_num": 1,
            "grade": grade,
            "text": "",
            "timeLimit": "100ms",
            "spaceLimit": "1M",
            "time_complexity": "o(n)",
            "space_complexity": "o(n)",
            "code_type": "python",
            "input_range": "none"
        }
    return data


# 发送请求
def send_request(data):
    Body = {
        "Body": data
    }
    start_time = time.time()  # 记录开始时间
    # 发送POST请求
    response = requests.post(url, json=Body)
    end_time = time.time()  # 记录结束时间
    response_json = response.json()
    elapsed_time = end_time - start_time
    if response_json['success']:
        write_excel(response_json, elapsed_time)


# 将返回值写入excel
def write_excel(response_json, elapsed_time):
    # 获取返回的JSON数据

    df_to_add = pd.DataFrame(response_json['data'])
    df_to_add['耗时'] = elapsed_time  # 将耗时添加到最后一列

    with pd.ExcelWriter(excel_filename, mode='a', engine='openpyxl', if_sheet_exists='overlay') as writer:
        sheet = writer.sheets['Sheet1']
        row_count = sheet.max_row
        # 将新的DataFrame写入Excel文件的新的一行
        # 如果Excel文件是空的，那么这里还会创建一个header
        df_to_add.to_excel(writer, sheet_name='Sheet1', index=False, header=False, startrow=row_count + 1)


for i in range(1, 200):
    data = build_request()
    send_request(data)
    print("完成写入", i)


# import pandas as pd
#
# if __name__ == '__main__':
#     t = {
#         "Options": [
#             "A. 数据清洗",
#             "B. 数据转换",
#             "C. 数据归一化",
#             "D. 所有选项都正确"
#         ],
#         "analyze": [
#             "数据预处理是机器学习中的一个重要步骤，包括数据清洗、数据转换和数据归一化等。"
#         ],
#         "answer": [
#             "C"
#         ],
#         "knowledge": "数据预处理",
#         "stem": "在机器学习中，数据预处理的步骤包括哪些？",
#         "template_out": "在机器学习中，数据预处理的步骤包括：\nA. 数据清洗\nB. 数据转换\nC. 数据归一化\nD. 所有选项都正确"
#     }
#
#     df = pd.read_excel('op.xlsx', header=None)
#     data = []
#     for index, row in df.iterrows():
#         Options = []
#         stem = ''
#         answer = []
#         try:
#             if index == 0:
#                 continue
#             stem = row[2]
#             answer.append(row[4])
#             Options.append(row[5])
#             Options.append(row[6])
#             Options.append(row[7])
#             Options.append(row[8])
#             my_logger.info(stem)
#             my_logger.info(answer)
#             my_logger.info(Options)
#             t = {
#                 "Options": Options,
#                 "analyze": [
#                     "数据预处理是机器学习中的一个重要步骤，包括数据清洗、数据转换和数据归一化等。"
#                 ],
#                 "answer": answer,
#                 "knowledge": "数据预处理",
#                 "stem": stem,
#                 "template_out": "在机器学习中，数据预处理的步骤包括：\nA. 数据清洗\nB. 数据转换\nC. 数据归一化\nD. 所有选项都正确"
#             }
#             i = 0
#             while True:
#                 res = judge_answer(t)
#                 if res['success']:
#                     if res['data']['correct']:
#                         data.append(row)
#                     else:
#                         answer.clear()
#                         t = res['data']['answer']
#                         my_logger.info(t)
#                         answer.append(t)
#                         my_logger.info(f'{res}, 下标：{row[0]}')
#                     break
#                 else:
#                     my_logger.info(f'请求错误{res}下标：{row[0]}')
#                 i += 1
#                 if i >= 3:
#                     raise Exception
#         except Exception as e:
#             print(e)
#             df_processed = pd.DataFrame(data)
#             df_processed.to_excel(f'output{index}.xlsx', index=False, header=False)
#             break
#     df_processed = pd.DataFrame(data)
#     df_processed.to_excel(f'output{index}.xlsx', index=False, header=False)